package com.example.testapp.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.study.LifeNewsDetailActivity;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.http.Contacts;
import com.example.testapp.activity.model.LifeNews;
import com.example.testapp.activity.model.LifeNewsList;
import com.example.testapp.activity.util.DisplayUtil;
import com.example.testapp.activity.view.listview.PullToRefreshAdapterViewBase;
import com.example.testapp.activity.view.listview.PullToRefreshBase;
import com.example.testapp.activity.view.listview.PullToRefreshListView;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

/**
 * Created by l on 2016/11/3.
 */

public class LifeNewFragment extends SuperFragment {

    private PullToRefreshListView mListView;
    private NewsAdapter   mAdapter;
    private ArrayList<LifeNews>  mList = new ArrayList<>();

    private int channelId; // 新闻 = 5，社区 = 27，房产 = 23,娱乐 = 21，汽车 = 24，
    private int requiredPage = 1;

    private RelativeLayout  mViewContainer;
    private LinearLayout    mFooterView;   //最后一条listview

    public LifeNewFragment(){ }

    public LifeNewFragment(int channelId) {
        this.channelId = channelId;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View  rootView = inflater.inflate(R.layout.fragment_life_news_list, container, false);
        mViewContainer = (RelativeLayout)rootView.findViewById(R.id.container);
        DisplayUtil.init(mContext);
        loadLifeNewsInfo(true);
        return rootView;
    }

    /**
     * 加载生活新闻信息
     */
    private void loadLifeNewsInfo(final boolean clean) {
        String  url = Contacts.BEFORE_PATH + channelId + Contacts.AFTER_PATH + requiredPage;
        AsyncHttpUtil.get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                 try {
                      if (clean){
                          mList.clear();
                      }
                     Gson gson = new Gson();
                     LifeNewsList mLifeNewsList = gson.fromJson(new String(responseBody), LifeNewsList.class);
                     if (mLifeNewsList != null){
                         ArrayList<LifeNews> list = mLifeNewsList.getList();
                         if (list != null && list.size() > 0){
                             requiredPage++;
                             mList.addAll(list);
                             initListView(); // 初始化页面
                         }else{
                             requiredPage = 0;
                             if (mList == null && mList.size() > 0){
                                 initNetErro();
                             }
                         }
                     }
                 }catch (Exception e){
                     e.printStackTrace();
                     if (mList == null && mList.size() == 0){
                         initNetErro();
                     }
                 }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (mList == null && mList.size() == 0){
                    initNetErro();
                }
            }
        });
    }

    private void initListView() {
        if (mContext == null)
              return;
         if (mFooterView != null){
             mListView.getRefreshableView().removeFooterView(mFooterView);
             mFooterView = null;
         }
         if (mListView != null)
             mListView.onRefreshComplete();

        View view = LayoutInflater.from(mContext).inflate(R.layout.view_header_list_item, null);
        mListView = (PullToRefreshListView) view.findViewById(R.id.news_list);
        mAdapter = new NewsAdapter();
        mListView.setAdapter(mAdapter);

        if (mViewContainer != null){
            mViewContainer.removeAllViews();
            mViewContainer.addView(view);
        }

        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                   if (refreshView.isHeaderShown()){
                       requiredPage = 1;
                       loadLifeNewsInfo(true);
                   }
            }
        });
       mListView.setOnPreRefreshingAnimListener(new PullToRefreshAdapterViewBase.OnPreRefreshingAnimListener() {
           @Override
           public void onPreRefreshingAnim() {
              mListView.setFooterLoadingViewHeaderText("加载更多信息");
           }
       });
        mListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                  if (requiredPage != 0){
                      //滑动到底部自动刷新
                      loadLifeNewsInfo(false);
                  }else{
                      //没有下一页了
                      mListView.onRefreshComplete();
                      if (mFooterView == null){
                          mFooterView = (LinearLayout) View.inflate(mActivity, R.layout.item_pull_to_refresh_footer, null);
                          TextView footer = (TextView) mFooterView.findViewById(R.id.footer);
                          footer.setText("到底了呢共" + mList.size() + "条新闻");
                          mListView.getRefreshableView().addFooterView(mFooterView);
                      }
                  }
            }
        });
    }

    private void initNetErro() {
        View netErrorView = LayoutInflater.from(mContext).inflate(R.layout.layout_load_noorder, null);
        if (mViewContainer != null){
            mViewContainer.removeAllViews();
            mViewContainer.addView(netErrorView);
        }
    }

    public class NewsAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null){
                convertView = View.inflate(mContext, R.layout.item_life_news_list, null);
                holder = new ViewHolder();
                holder.imgNewsPic = (ImageView)convertView.findViewById(R.id.imgNewsPic);
                holder.title = (TextView)convertView.findViewById(R.id.tvTitle);
                holder.date_text = (TextView)convertView.findViewById(R.id.date_text);
                holder.description = (TextView)convertView.findViewById(R.id.tvDescription);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            LifeNews item = mList.get(position);
            if (!TextUtils.isEmpty(item.getImage().getSrc())){
                Picasso.with(mContext).load(item.getImage().getSrc()).placeholder(R.color.ECECEC).error(R.color.ECECEC).into(holder.imgNewsPic);
            }
            holder.title.setText(item.getTitle());
            holder.date_text.setText(item.getDate());
            holder.description.setText(item.getContent());
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, LifeNewsDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("newsId", mList.get(position).getNewsId());
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
                }
            });
            return convertView;
        }

        public class ViewHolder{
            ImageView imgNewsPic;
            TextView  title;
            TextView  date_text;
            TextView  description;
        }
    }
}
